﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using ComicQ.Controller;
using ComicQ.Domain.Table;

namespace ComicQ.Dektop.View
{
    /// <summary>
    /// Interaction logic for RentView.xaml
    /// </summary>
    public partial class RentView
    {
        private readonly RentController _rentControl;
        private IList<Rent> _rents;

        public RentView()
        {
            InitializeComponent();

            _rentControl = new RentController();
            _rents = _rentControl.GetAllRent();
            dataGridRent.ItemsSource = _rents;
        }

        private void RefreshGrid()
        {
            dataGridRent.ItemsSource = null;
            _rents = _rentControl.GetAllRent();
            dataGridRent.ItemsSource = _rents;
        }

        private void ButtonAddClick(object sender, RoutedEventArgs e)
        {
            var newWindow = new RentEditorView();

            if (newWindow.ShowDialog() != false)
            {
            }
            else
            {
                RefreshGrid();
            }
        }

        private void ButtonDeleteClick(object sender, RoutedEventArgs e)
        {
            try
            {
                if (dataGridRent.SelectedItem == null)
                    throw new NullReferenceException();

                var rent = _rents
                        .Where(r => r.Id == _rents[dataGridRent.SelectedIndex].Id)
                        .Select(r => r)
                        .Single();

                _rentControl.DeleteRent(rent);
                MessageBox.Show("sukses menghapus rent");
                RefreshGrid();
            }
            catch (NullReferenceException)
            {
                MessageBox.Show("pilih yang mau didelete");
            }
        }

        private void ButtonEditClick(object sender, RoutedEventArgs e)
        {
            try
            {
                if (dataGridRent.SelectedItem == null)
                    throw new NullReferenceException();

                var newWindow = new RentEditorView(_rents[dataGridRent.SelectedIndex]);

                if (newWindow.ShowDialog() != false)
                {
                }
                else
                {
                    RefreshGrid();
                }
            }
            catch (NullReferenceException)
            {
                MessageBox.Show("pilih yang mau diedit");
            }
        }
    }
}
